package com.irishud.hudnavi.udp;

import android.content.Context;
import android.hardware.hdmi.HdmiRecordListener;
import android.net.wifi.WifiManager;
import android.util.Log;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.SocketException;
import java.net.UnknownHostException;

/**
 * Created by Administrator on 2016/10/11.
 */


public class MulticastReceiver extends Thread{
    String Tag = "MulticastReceiver";

    public interface OnMulticastReceiveListener{
        void onMulticastSocketReceive(byte[] data,int len);
    }

    OnMulticastReceiveListener listener;
    MulticastSocket socket;
    WifiManager.MulticastLock lock;
    String ip;
    int port;
    Context context;

    public MulticastReceiver(Context ctx,String ip,int port){
        context = ctx.getApplicationContext();
        WifiManager manager = (WifiManager) context
                .getSystemService(Context.WIFI_SERVICE);
        lock= manager.createMulticastLock("test_wifi");
        this.ip = ip;
        this.port = port;
        Log.e(Tag, "multicast receiver run:@" + ip +":"+port);
    }

    public void setListener(OnMulticastReceiveListener listener){
        this.listener = listener;
    }

    @Override
    public void run() {
        super.run();
        try {
            InetAddress group = InetAddress.getByName(ip);
            byte[] buff = new byte[1024];
            socket = new MulticastSocket(port);
            socket.setBroadcast(true);
            DatagramPacket datagramPacket = new DatagramPacket(buff, 1024, group, 30001);
            socket.joinGroup(group);
            while (true) {
                lock.acquire();
                Log.e(Tag, "wait for msg");
                socket.receive(datagramPacket);
                final String msg = new String(datagramPacket.getData());
                Log.e(Tag, "multicast get:" + msg);
                if(listener!=null){
                    listener.onMulticastSocketReceive(datagramPacket.getData(),datagramPacket.getLength());
                }
                lock.release();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}